package com.quectel.taskserver.job.patrol;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.quectel.constant.core.grid.GridPlanTaskConstant;
import com.quectel.core.module.grid.dto.GridPlanTaskDto;
import com.quectel.core.module.grid.service.GridPlanTaskService;
import com.quectel.util.common.DateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/2/17 13:29
 * 网格巡检漏检任务扫描
 * <p>
 * 搜索条件：
 * 1、查询昨天的任务
 * 2、任务执行状态不是2（已完成）
 * <p>
 * 操作：
 * 1、把任务更新为结束
 */
@Component
public class GridPatrolMissedDetectionTask implements SimpleJob {
    private static final Logger LOGGER = LoggerFactory.getLogger(GridPatrolMissedDetectionTask.class);

    @DubboReference
    private GridPlanTaskService gridPlanTaskService;

    @Override
    public void execute(ShardingContext shardingContext) {
        gridPatrolMissedDetectionTask();
    }

    public void gridPatrolMissedDetectionTask() {
        DateTime yesterday = DateUtil.yesterday();
        String yesterDayStr = new SimpleDateFormat(DateUtils.FormatType.SIMPLE.getType())
                .format(yesterday);
        LOGGER.info("网格巡更扫描漏检任务开始执行...扫描时间为{} 的巡检任务", yesterDayStr);

        List<GridPlanTaskDto> result = new ArrayList<>();
        // 查询昨天的
        // 未执行或者执行中  的任务
        int pageNo = 1;
        while (true) {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("startTime", yesterDayStr);
            queryMap.put("endTime", yesterDayStr);
            queryMap.put("offset", (pageNo - 1) * 2000);
            queryMap.put("limit", 2000);
            List<GridPlanTaskDto> list = gridPlanTaskService.queryList(queryMap);
            if (list.size() <= 0) {
                break;
            }
            result.addAll(list);
            pageNo++;
        }

        // 状态不是已完成的记录
        List<GridPlanTaskDto> filterTaskList =
                result.stream().filter((o) -> !o.getExecStatus().equals(GridPlanTaskConstant.TasksExecStatusEnum.STATUS_EXECUTED.getStatus())).collect(Collectors.toList());

        LOGGER.info("要执行漏检的巡更任务的条数{}", filterTaskList.size());
        // 满足总数和已执行不相等
        if (CollectionUtils.isNotEmpty(filterTaskList)) {
            for (GridPlanTaskDto taskDto : filterTaskList) {
                try {
                    // 更新状态为漏检
                    GridPlanTaskDto updately = new GridPlanTaskDto();
                    updately.setId(taskDto.getId());
                    updately.setExecStatus(GridPlanTaskConstant.TasksExecStatusEnum.STATUS_MISSED_DETECTION.getStatus());
                    gridPlanTaskService.updateById(updately);
                } catch (Exception e) {
                    continue;
                }
            }
        }
        LOGGER.info("{}安保巡更扫描漏检任务执行结束", yesterDayStr);

    }
}
